const express = require('express')
const article = express.Router()
const db = require('../db')
const { validation, dbPromise } = require('../utils')
const Joi = require('joi')


// 新增和修改文章
const article_schema = Joi.object({
    id: Joi.number().error(new Error('id不规范')),
    title: Joi.string().required().error(new Error('文章名称不能为空')),
    content: Joi.string().required().error(new Error('文章内容不能为空')),
    cover_img: Joi.string().error(new Error('封面图片不准确')),
    create_time: Joi.string().error(new Error('创建时间不准确')),
    state: Joi.number().error(new Error('状态码不准确')),
    isdel: Joi.number().error(new Error('删除码不准确')),
    cate_id: Joi.number().error(new Error('分类id不准确')),
    author_id: Joi.number().error(new Error('作者id不准确')),
})
// 新增/修改
article.post('/article', validation(article_schema), async (req, res) => {
    try {
        // 判断分类id和作者id是否存在
        const { cate_id, author_id } = req.body;
        const cateResult = await dbPromise(`select * from ev_article_cate where id = ${cate_id}`)
        const authorResult = await dbPromise(`select * from ev_users where id = ${author_id}`)
        if (cateResult.length !== 1) return res.cc('没有该分类id')
        if (authorResult.length !== 1) return res.cc('没有该作者')

        await dbPromise("INSERT INTO ev_article set ? ON DUPLICATE KEY UPDATE ?", [req.body, req.body]);
        res.send({ code: 200, msg: '成功', data: req.body })
    } catch (err) {
        res.cc(err)
    }
})

// 文章列表
article.get("/article", async (req, res) => {
    try {
        const count = await dbPromise("SELECT COUNT(id) as total FROM ev_article where isdel != 1")
        const total = count[0].total

        const { id, pageNum = 1, pageSize = 10 } = req.query
        const sql = id ?
            'select a.*,u.username as author_name from ev_article a inner join ev_users u on u.id = a.id where a.id = ? and a.isdel != 1' :
            `select a.*,u.username as author_name from ev_article a inner join ev_users u on u.id = a.id where a.isdel != 1 order by a.id desc limit ${pageSize} offset ${pageSize * (pageNum - 1)}`
        const result = await dbPromise(sql, [id])

        res.send({ code: 200, msg: '成功', data: { result, total, pageSize, pageNum } })
    } catch (err) {
        return res.cc(err)
    }
})

// 删除文章
const article_del_schema = Joi.object({
    id: Joi.number().required().error(new Error('id错误'))
})
article.delete('/article', validation(article_del_schema), (req, res) => {
    const id = req.query.id
    db.query('update ev_article set ? where id = ?', [{ isdel: 1 }, req.query.id], (err, result) => {
        if(err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('没有该id数据')
        res.send({ code: 200, msg: '成功', data: { id } })
    })
})

module.exports = article